package cn.gzjp.modules.woms.scheduler;

import cn.gzjp.common.config.Global;
import cn.gzjp.common.constant.Constants;
import cn.gzjp.common.constant.Constants.EventStatus;
import cn.gzjp.modules.woms.entity.Event;
import cn.gzjp.modules.woms.entity.Worker;
import cn.gzjp.modules.woms.service.EventService;
import cn.gzjp.modules.woms.service.WorkerService;
import cn.gzjp.modules.wx.service.QyWxService;
import cn.hutool.core.util.StrUtil;
import me.chanjar.weixin.common.api.WxConsts;
import me.chanjar.weixin.common.exception.WxErrorException;
import me.chanjar.weixin.cp.bean.WxCpMessage;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Lazy;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;

/**
 * 定时任务
 * 
 * @author zengcp
 *
 */
@Service
@Lazy(false)
public class TaskJob {
	
	public static Logger log = LoggerFactory.getLogger("jobLog");

	@Autowired
	private EventService eventService;

	@Autowired
	private QyWxService qyWxService;
	@Autowired
	private WorkerService workerService;

	@Scheduled(cron = "0 0/30 * * * ?")
	public void exec() {
		log.info("工单未处理任务提醒开始");
		Event search = new Event();
		search.setPmUnfinish("y");
		List<Event> eventList = eventService.findList(search);
		for(Event event:eventList){
			if(event.getLeftMinutes()<=480){
				if(EventStatus.create.equals(event.getStatus())){//创建 状态，对分派员进行提醒
					//推送消息给分派员
					Worker worker = new Worker();
					worker.setRoles(Constants.WorkerRole.assigner);
					worker.setProjectId(event.getOperationArea());
					List<Worker> assignerList = workerService.findList(worker);
					for(Worker assigner:assignerList){
						sendQyWxMessage(event, Constants.AgentId.assigner,"工单待分派","您有新的工单还未分派"+event.getDeviceName()+"设备出现故障,请尽快处理",assigner.getId());
					}
				}
				if(EventStatus.assign.equals(event.getStatus())) {//分派员已分派状态，推送给外场运维人员提醒要接收
					String []enginers = event.getEngineerIds().split("\\|");
					if(enginers!=null&&enginers.length>0){
						List<String> enginersList = Arrays.asList(enginers);
						for(String engineerId:enginersList){
							//推送消息
							sendQyWxMessage(event, Constants.AgentId.enginer,"工单待处理","您有新的工单还未处理"+event.getDeviceName()+"设备出现故障,请尽快处理",engineerId);
						}
					}
				}
				if(EventStatus.process.equals(event.getStatus())) {//处理中,推送给外场运维人员，提醒去处理
					//推送消息
					sendQyWxMessage(event, Constants.AgentId.enginer,"工单未处理完成","您有工单还未处理完成"+event.getDeviceName()+"设备出现故障,请尽快处理",event.getReceiverId());
				}
				if(EventStatus.complete.equals(event.getStatus())) {//处理完成，待确认，推送给内存运营人员 提醒修复确认
					//推送消息
					sendQyWxMessage(event, Constants.AgentId.achieve,"工单待确认","您有新的工单待修复确认"+event.getDeviceName()+"设备出现故障已处理完,请尽快确认",event.getCreaterId());
				}
			}

		}


		log.info("定时任务提醒结束");

	}


	//下发企业推送
	private void sendQyWxMessage(Event event, String agentId, String title,String content,String toUser){
		WxCpMessage message = new WxCpMessage();
		message.setAgentId(agentId);
		message.setMsgType(WxConsts.CUSTOM_MSG_NEWS);
		WxCpMessage.WxArticle article = new WxCpMessage.WxArticle();
		if(StrUtil.isNotBlank(event.getFaultPic())){
			article.setPicUrl(Global.getConfig("projectUrl")+"/static/front/cms/img/event_default.png");
		}
		article.setDescription(content);
		article.setTitle(title);
		String uri = "";
		if(Constants.AgentId.assigner.equals(agentId)){
			uri = "assigner";

		}else if(Constants.AgentId.pm.equals(agentId)){
			uri = "pm";

		}else if(Constants.AgentId.enginer.equals(agentId)){
			uri = "engineer";

		}
		else if(Constants.AgentId.achieve.equals(agentId)){
			uri = "achieve";

		}
		article.setUrl(Global.getConfig("projectUrl") + Global.getFrontPath()+"/"+uri+"/event?id=" + event.getId()+"&userId="+toUser+"&agentId="+agentId);
		List<WxCpMessage.WxArticle> articles = new ArrayList<WxCpMessage.WxArticle>();
		articles.add(article);
		message.setArticles(articles);
		message.setToUser(toUser);

		boolean corpDebug = Boolean.valueOf(Global.getConfig("corp.debug"));
		String corpId = Global.getConfig("corp.id");

		if(!corpDebug){//测试模式, 发不了通知
			try {
				qyWxService.messageSend(corpId, agentId, message);
			} catch (WxErrorException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
		}

	}
}
